express = require 'express'
router = express.Router()

crypto = require 'crypto'

log4js = require 'log4js'
log4js.loadAppender 'file'
log4js.addAppender (log4js.appenders.file 'log/signup.log'),'signup'


schema = require '../modules/schema.js'
Student = schema.Student
Teacher = schema.Teacher
Key = schema.Key
SC = schema.SC
Course = schema.Course

Handler = require '../modules/err_handler.js'
errHandler = Handler.errHandler
dataHandler = Handler.dataHandler

Check = require '../modules/login_check.js'
checkLogin = Check.checkLogin
notLogin = Check.notLogin



#help
router.get '/student/help',(req,res)->
	res.render 'student/help',{}


# check login

router.get '/student/login',notLogin
router.post '/student/login',notLogin

# login module

router.post '/student/login',(req,res) ->
	console.log req.body
	if not req.body.sid or not req.body.passwd
		req.session.err = '请正确输入学号和密码'
		errHandler req,res
	else
		Student.findOne '_id':req.body.sid
			.exec (err,student)->
				if err
					req.session.err = '请输入正确的学号和密码!'
					errHandler req,res
				else
					if not student
						req.session.err = '请输入正确的学号和密码!'
						errHandler req,res
					else
						md5 = crypto.createHash 'md5'
						md5.update req.body.passwd
						passwd = md5.digest 'hex'
						if passwd is student.passwd
							req.session.user = student
							req.session.type = 's'
							if req.session.sc?
								cid = req.session.sc
								req.session.sc = null
								Course.findOne "_id":cid
									.exec (err,course)->
										if err?
											console.log "co err"
											console.log err
											dataHandler res,'redirect','/student'
										else if not course?
											req.session.err = "no this course!"
											errHandler req,res
										else
											sc = new SC
																	student : req.session.user._id,
																	course : course._id
											sc.save (err)->
												if err?
													console.log "sc err"
													console.log err
													dataHandler res,'redirect','/student'
												else
													dataHandler res,'redirect','/student'
							else
								dataHandler res,'redirect','/student'
						else
							req.session.err = '请输入正确的学号和密码!'
							errHandler req,res

router.get '/student/addCourse/:cid',(req,res,next)->
	if req.session.user? && req.session.type is 's'
		Course.findOne "_id":req.param "cid"
			.exec (err,course)->
				if err?
					req.session.err = err
					errHandler req,res
				else if not course?
					res.redirect '/student'
				else
					sc = new SC
											student : req.session.user._id,
											course : course._id
					sc.save ()->
							res.redirect "/student"
	else
		req.session.sc = req.param "cid"
		next()

# check login
isStudent = (req,res,next)->
	if req.session.type isnt 's'
		req.session.sc = null
		req.session.user = null
		req.session.type = null
		res.redirect '/'
	else
		next()

router.get '/student',checkLogin
router.all '/student/*',checkLogin
router.get '/student',isStudent
router.all '/student/*',isStudent


# main page

router.get '/student',(req,res) ->
	res.render 'student/index','student':req.session.user

router.get '/student/getCourse',(req,res)->
	SC.find 'student':req.session.user._id
		.populate 'course','cname'
		.exec (err,sc)->
			if err?
				req.session.err = err
				errHandler req,res
			else if not sc?
				dataHandler res,'ok',0
			else
				dataHandler res,'ok',sc

router.post '/student/course/:cid/ill',(req,res)->
	SC.findOne {course:req.param('cid'),student:req.session.user._id}
		.exec (err,course)->
			if err?
				req.session.err = err
				errHandler req,res
			else if not course?
				req.session.err = 'you didn\'t pick this course'
				errHandler req,res
			else
				month = req.body.m/1
				day = req.body.d/1
				if month >12 or month <= 0 or day > 31 or day <= 0
					req.session.err = 'input date error!'
					errHandler req,res
				else
					Course.findOne {_id:req.param 'cid'}
						.exec (err,c)->
							if err?
								req.session.err = err
								errHandler req,res
							else
								SC.update {course:req.param('cid'),student:req.session.user._id},{"$set":{nextIll:{time:c.signup_times+1,MD:"#{month}-#{day}",logd:false}}}
									.exec (err)->
										if err?
											req.session.err
											errHandler req,res
										else
											dataHandler res,"ok",{}

router.get '/student/course/:cid',(req,res)->
	SC.findOne 'course':req.param('cid'),'student':req.session.user._id
			.populate 'course'
			.exec (err,sc)->
				if err?
					req.session.err = err
					errHandler req,res
				else
					if not sc?
						req.session.err = "you didn't pick this course"
						errHandler req,res
					else
						res.render 'student/course','student':req.session.user,'sc':sc


# interface
router.get '/student/interface/info',(req,res)->
	if req.session.type is 's'
		st =
			sid:req.session.user._id
			sname:req.session.user.sname
		dataHandler res,"ok",st
	else
		req.session.err = "你不是学生"
		errHandler req,res

router.get '/student/interface/courseInfo/:cid',(req,res)->
	if req.param('cid')?
		SC.findOne 'course':req.param('cid'),'student':req.session.user._id
			.populate 'course'
			.exec (err,sc)->
				if err?
					req.session.err = err
					errHandler req,res
				else if not sc?
					req.session.err = "you didn't pick this course"
					err_handler req,res
				else
					dataHandler res,'ok',sc


				
# course

router.post '/student/addCourse',(req,res) ->
	if not req.body.cid
		req.session.err = '请输入正确的课程号!'
		errHandler req,res
	else
		Course.findOne '_id':req.body.cid
			.exec (err,course) ->
				if err
					if err.message.match /Cast to ObjectId failed for value/
						req.session.err = '请输入正确的课程号!'
					else
						req.session.err = err
						errHandler req,res
				else
					if not course
						req.session.err = '查无此课'
						errHandler req,res
					else
						sc = new SC
												student : req.session.user._id,
												course : course._id
						sc.save (err)->
							if err
								req.session.err = "你已经选了 #{course.cname} 或数据库错误"
								errHandler req,res
							else
								dataHandler res,'ok',course.cname

#signup

router.post '/student/confirm/',(req,res)->
	info = {}
	logger = log4js.getLogger 'confirm'
	logger.setLevel 'debug'
	logger.debug "#{req.session.user._id} is try our key"
	Key.findOne '_id':req.body.key
		.exec (err,key)->
			if err
				req.session.err = err
				errHandler req,res
			else
				if not key
					req.session.err = '请输入正确的激活码'
					errHandler req,res
				else
					if key.cid? && key.cid != ""
						Course.findOne '_id':key.cid
							.exec (err,course)->
								if err?
									req.session.err = err
									errHandler req,res
								else
									info.cname = course.cname
									info.times = key.time
									dataHandler res,'confirm',info
					else
						info.cname = '老师尚未绑定的课程'
						info.times = 0
						dataHandler res,'confirm',info

router.post '/student/signup',(req,res)->
	if req.session.type isnt 's'
		req.session.type = null
		req.session.user = null
		res.redirect '/'
	else
		logger = log4js.getLogger 'signup'
		logger.setLevel 'debug'
		Key.findOne _id:req.body.key
			.exec (err,key)->
				if err
					req.session.err = err
					errHandler req,res
				else if not key?
					logger.debug "#{req.session.user._id} input a wrong key"
					req.session.err = '请输入正确的激活码'
					errHandler req,res
				else
					if key.cid && key.cid != ''
						SC.update student :req.session.user._id,course :key.cid,
							'$addToSet': signup: time:key.time,_id:key._id,
							(err,sc)->
								if err
									req.session.err = err
									errHandler req,res
								else if sc.nModified isnt 0 && sc.n isnt 0
									logger.debug "#{req.session.user._id} sign #{key.cid} time #{key.time} with key #{key._id}"
									key.remove ()->
										dataHandler res,'ok','签到成功'
								else
									logger.debug "#{req.session.user._id} didn't pick course(#{key.cid}) and I help him pick it"
									logger.debug "#{req.session.user._id} sign #{key.cid} time #{key.time} with key #{key._id}"
									_sc = new SC {student:req.session.user._id,course:key.cid,signup:[{time:key.time,_id:key._id}]}
									_sc.save (err)->
										if err
											logger.error err
											req.session.err = err
											errHandler req,res
										else
											key.remove ()->
												dataHandler res,'ok','签到成功'
					else if key.Tmp is not ""
						req.session.err = "this key had being used by #{key.Tmp}"
						errHandler req,res
					else
						logger.debug "#{req.session.user._id} sign tmp #{key.Tmp} with key #{key._id}"
						Key.update "_id":req.body.key,
							'$set': signs:req.session.user._id,
							(err,key)->
								if err?
									req.session.err = err
									errHandler req,res
								else if key?
									dataHandler res,'ok','签到成功'
								else
									req.session.err = 'no this key!'
									errHandler req,res


#get unbinding keys for student
router.get '/student/unbinding',(req,res)->
	Key.count({"signs":req.session.user._id}).exec (err,number)->
		dataHandler res,"log",number


module.exports = router
							




